//
//  YDAddTryDriveController.m
//  YDTestDrive
//
//  Created by ios on 2017/2/15.
//  Copyright © 2017年 ios. All rights reserved.
//

#import "YDAddTryDriveController.h"
#import "YDChooseCarController.h"
#import "YDCustomerScanController.h"

#import "CustomSheetView.h"

#import "YDPassengerModel.h"

#import "AFNetworking.h"
#import "NSString+Mobile.h"
#import "UIImageView+WebCache.h"

@interface YDAddTryDriveController () <CustomSheetViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>

//点击图片放大使用的
{
    UIView *blackBGView;
    UIView *coverView;
    UIImageView *bigImageView;
    CGRect imageInWindowFrame;
    CGSize imageBigSize;
}

@property (weak, nonatomic) IBOutlet UIImageView *cardImageView1;
@property (weak, nonatomic) IBOutlet UIImageView *cardImageView2;
@property (weak, nonatomic) IBOutlet UIImageView *cardImageView3;

@property (weak, nonatomic) IBOutlet UIButton *deleteButton1;
@property (weak, nonatomic) IBOutlet UIButton *deleteButton2;
@property (weak, nonatomic) IBOutlet UIButton *deleteButton3;

@property (weak, nonatomic) IBOutlet UIButton *addImageButton;


@property (nonatomic, strong) UIButton *rightButton;

@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *carNameTextField;

@property (nonatomic, copy) NSString *imageName1;
@property (nonatomic, copy) NSString *imageName2;
@property (nonatomic, copy) NSString *imageName3;

@property (nonatomic, assign) NSInteger selectImageIndex;

/**
 新增试驾参数
 */
@property (nonatomic, strong) NSMutableDictionary *addParameters;


@end

@implementation YDAddTryDriveController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    _addParameters = [NSMutableDictionary dictionary];
    [_addParameters setValue:@"" forKey:@"customerId"];
    [_addParameters setValue:@"" forKey:@"passengerId"];
    
    self.title = @"试驾登记";
    
    [self setupView];
    
#warning 客流ID在才开始时如果有就带
    [_addParameters setValue:self.passengerModel.modelId forKey:@"passengerId"];

    if (self.passengerModel.customerPhone.length > 0) {
        [self searchPhone:self.passengerModel.customerPhone];
    } else {
        [self setupCustomerDefault];
    }

}

- (void)setupCustomerDefault
{
    if (self.passengerModel) {
        self.nameTextField.text = self.passengerModel.customerName;
        self.phoneTextField.text = self.passengerModel.customerPhone;
        self.carNameTextField.text = self.passengerModel.cartypeName;
        
        if (self.passengerModel.customerPhone.length > 0) {
            self.nameTextField.enabled = NO;
            self.phoneTextField.enabled = NO;
        }
        
        //图片显示
        NSArray *imageURLArray = [self.passengerModel.licenceImgUrl componentsSeparatedByString:@","];
        if (imageURLArray.count >= 1) {
            if ([imageURLArray[0] length] <= 0) return;
            [self.cardImageView1 sd_setImageWithURL:[NSURL URLWithString:imageURLArray[0]] placeholderImage:[UIImage imageNamed:@"frame_upload"]];
            self.addImageButton.frame = self.cardImageView2.frame;
            self.deleteButton1.hidden = NO;
        }
        if (imageURLArray.count >= 2) {
            [self.cardImageView2 sd_setImageWithURL:[NSURL URLWithString:imageURLArray[1]] placeholderImage:[UIImage imageNamed:@"frame_upload"]];
            self.addImageButton.frame = self.cardImageView3.frame;
            self.deleteButton2.hidden = NO;
        }
        if (imageURLArray.count >= 3) {
            [self.cardImageView3 sd_setImageWithURL:[NSURL URLWithString:imageURLArray[2]] placeholderImage:[UIImage imageNamed:@"frame_upload"]];
            self.addImageButton.frame = CGRectZero;
            self.deleteButton3.hidden = NO;
        }
        
        //图片名参数
        NSArray *imageNameArray = [self.passengerModel.licenceImg componentsSeparatedByString:@","];
        if (imageNameArray.count >= 1) {
            self.imageName1 = imageNameArray[0];
        }
        if (imageNameArray.count >= 2) {
            self.imageName2 = imageNameArray[1];
        }
        if (imageNameArray.count >= 3) {
            self.imageName3 = imageNameArray[2];
        }

        
        [_addParameters setValue:self.passengerModel.customerName forKey:@"customerName"];
        [_addParameters setValue:self.passengerModel.customerPhone forKey:@"customerPhone"];
        [_addParameters setValue:self.passengerModel.customerId forKey:@"customerId"];
        [_addParameters setValue:self.passengerModel.brandId forKey:@"brandId"];
        [_addParameters setValue:self.passengerModel.carsId forKey:@"carsId"];
        [_addParameters setValue:self.passengerModel.cartypeId forKey:@"cartypeId"];
    }
}

- (void)setupView
{
    _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightButton.frame = CGRectMake(0, 0, 50.0f, 24.0f);
    [_rightButton setTitle:@"     提交" forState:UIControlStateNormal];
    _rightButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [_rightButton setTitleColor:[UIColor colorWithHexString:@"a0abbf"] forState:UIControlStateNormal];
    [_rightButton addTarget:self action:@selector(rightButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightButton];
    
    self.nameTextField.delegate = self;
    self.phoneTextField.delegate = self;
    
    //初始化一个用来当做背景的View
    blackBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    blackBGView.backgroundColor = [UIColor clearColor];
    blackBGView.hidden = YES;
    [kWindow addSubview:blackBGView];
    
    //黑色背景，渐变
    coverView = [[UIView alloc] initWithFrame:blackBGView.bounds];
    coverView.backgroundColor = [UIColor blackColor];
    [blackBGView addSubview:coverView];
    
    bigImageView = [[UIImageView alloc] init];
    [blackBGView addSubview:bigImageView];
    
    //添加点击手势（即点击图片后退出全屏）
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeView)];
    [blackBGView addGestureRecognizer:tapGesture];
    
    //添加点击手势(三个ImageView的交互属性在xib文件中打开的)
    UITapGestureRecognizer *imageTap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    UITapGestureRecognizer *imageTap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    UITapGestureRecognizer *imageTap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.cardImageView1 addGestureRecognizer:imageTap1];
    [self.cardImageView2 addGestureRecognizer:imageTap2];
    [self.cardImageView3 addGestureRecognizer:imageTap3];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark 选择车型
- (IBAction)chooseCarButtonClick {
    
    [self.view endEditing:YES];
    
    YDChooseCarController *VC = [[YDChooseCarController alloc] init];
    VC.ChooseCarBlock = ^(NSString *brandID, NSString *carID, NSString *carTypeID, NSString *carName){
        
        [_addParameters setValue:brandID forKey:@"brandId"];
        [_addParameters setValue:carID forKey:@"carsId"];
        [_addParameters setValue:carTypeID forKey:@"cartypeId"];
        
        _carNameTextField.text = carName;
        
    };
    [self.navigationController pushViewController:VC animated:YES];
}

- (IBAction)addImageClick:(UIButton *)sender {
    
    [self.view endEditing:YES];
    
    if (sender.x == self.cardImageView1.x) {
        _selectImageIndex = 1;
    } else if (sender.x == self.cardImageView2.x) {
        _selectImageIndex = 2;
    } else if (sender.x == self.cardImageView3.x) {
        _selectImageIndex = 3;
    }
    
    
    CustomSheetView *sheet = [[CustomSheetView alloc] initWithBottomButtonCount:1 otherButtonTitleArray:@[@"拍摄",@"从相册中选择"]];
    sheet.delegate = self;
    [kWindow addSubview:sheet];
}


#pragma mark 点击提交
- (void)rightButtonClick
{
    _rightButton.enabled = NO;
    [self.view endEditing:YES];
    [self addTryDrive];
}

#pragma mark 提交试驾
- (void)addTryDrive
{
    if ([[self.addParameters valueForKey:@"customerName"] length] <= 0) {
        [MBProgressHUD showTips:@"请填写姓名" toView:self.view];
        _rightButton.enabled = YES;
        return;
    }
    if ([[self.addParameters valueForKey:@"customerPhone"] length] <= 0) {
        [MBProgressHUD showTips:@"请填写手机号" toView:self.view];
        _rightButton.enabled = YES;
        return;
    }
    if (![[self.addParameters valueForKey:@"customerPhone"] isMobilePhone]) {
        [MBProgressHUD showTips:@"请填写正确的手机号" toView:self.view];
        _rightButton.enabled = YES;
        return;
    }
    if (self.carNameTextField.text.length <= 0) {
        [MBProgressHUD showTips:@"请选择意向车型" toView:self.view];
        _rightButton.enabled = YES;
        return;
    }
    if (self.imageName1.length <= 0) {
        [MBProgressHUD showTips:@"请上传驾照图片" toView:self.view];
        _rightButton.enabled = YES;
        return;
    }
    
    if (self.imageName1.length > 0) {
        [self.addParameters setValue:[NSString stringWithFormat:@"%@",self.imageName1] forKey:@"licenceImg"];
    }
    if (self.imageName2.length > 0) {
        [self.addParameters setValue:[NSString stringWithFormat:@"%@,%@",self.imageName1,self.imageName2] forKey:@"licenceImg"];
    }
    if (self.imageName3.length > 0) {
        [self.addParameters setValue:[NSString stringWithFormat:@"%@,%@,%@",self.imageName1,self.imageName2,self.imageName3] forKey:@"licenceImg"];
    }
    
    NSString *URL = [NSString stringWithFormat:@"%@sid=%@", kAddTrailAddress, getNSUser(kAPP_SID)];
    
    [MBProgressHUD showStatus:@"" toView:self.view];
    [YDDataService POST:self.addParameters url:URL block:^(id result) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        _rightButton.enabled = YES;
        
        if ([[result valueForKey:@"code"] isEqualToString:@"S_OK"]) {
            
            NSDictionary *dicID = result[@"var"];
            YDCustomerScanController *VC = [[YDCustomerScanController alloc] initWithNibName:@"YDCustomerScanController" bundle:nil];
            VC.customerId = dicID[@"customerId"];
            VC.trialId = dicID[@"testDriveId"];
            [self.navigationController pushViewController:VC animated:YES];
            
        } else {
        
            [MBProgressHUD showTips:[NSString stringWithFormat:@"%@", [result valueForKey:@"code"]] toView:self.view];
        }
        
        
    } failBlock:^(id error) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        _rightButton.enabled = YES;
        [MBProgressHUD showTips:[NSString stringWithFormat:@"%@", error] toView:self.view];
    }];
}

#pragma mark - textField delegete
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //当前文字
    NSMutableString *currentString = [NSMutableString stringWithString:textField.text];
    
    if (string.length > 0) {
        //输入文字
        [currentString insertString:string atIndex:range.location];
    } else {
        //删除文字
        [currentString deleteCharactersInRange:range];
    }
    
    if (textField == self.phoneTextField) {
        //if (string.length == 0) return YES;
        
        if (currentString.length > 11) {
            return NO;
        }
        
        //如果是手机号码，查询这个号码
        if ([currentString isMobilePhone]) {
            [self searchPhone:currentString];
        }
        
        [self.addParameters setValue:currentString forKey:@"customerPhone"];
    }
    
    if (textField == self.nameTextField) {
        [self.addParameters setValue:currentString forKey:@"customerName"];
    }
    
    return YES;
}

#pragma mark - 查询客户信息
- (void)searchPhone:(NSString *)phone
{
    NSString *URL = [NSString stringWithFormat:@"%@sid=%@", kGetCustomerInfoAddress, getNSUser(kAPP_SID)];
    
    NSDictionary *dic = @{@"customerPhone" : phone};
    
    [YDDataService POST:dic url:URL block:^(id result) {
        
        if ([[result valueForKey:@"code"] isEqualToString:@"S_OK"]) {
            self.passengerModel = [YDPassengerModel instanceWithDict:[result valueForKey:@"var"]];
            [self setupCustomerDefault];
        }
    } failBlock:^(id error) {
        
    }];
}

#pragma mark - 点击图片放大图片
//点击图片后的方法(即图片的放大全屏效果) (图片的tag分别为101、102、103)
- (void)tapAction:(UITapGestureRecognizer *)tapGesture
{
    CGFloat imageX = self.cardImageView1.x;
    CGFloat imageY = self.cardImageView1.y + 64.0f + 243.0f;
    
    if (tapGesture.view.tag == 101)
    {
        if (self.cardImageView1.image == nil) return;
        
        bigImageView.image = self.cardImageView1.image;
        imageX = self.cardImageView1.x;
    }
    else if (tapGesture.view.tag == 102)
    {
        if (self.cardImageView2.image == nil) return;
        
        bigImageView.image = self.cardImageView2.image;
        imageX = self.cardImageView2.x;
    }
    else if (tapGesture.view.tag == 103)
    {
        if (self.cardImageView3.image == nil) return;
        
        bigImageView.image = self.cardImageView3.image;
        imageX = self.cardImageView3.x;
    }
    
    //计算image放大后的size
    CGFloat imageHeight = bigImageView.image.size.height / bigImageView.image.size.width * kScreenWidth;
    imageBigSize = CGSizeMake(kScreenWidth, imageHeight);
    
    imageInWindowFrame = CGRectMake(imageX, imageY, self.cardImageView1.width, self.cardImageView1.height);
    
    //计算点击的图片在整个屏幕的位置 和 图片放大后的大小 (放大和缩小用)
    bigImageView.frame = imageInWindowFrame;

    coverView.alpha = 0;
    blackBGView.hidden = NO;
    [UIView animateWithDuration:0.25f animations:^{
        coverView.alpha = 1.0f;
        bigImageView.size = imageBigSize;
        bigImageView.center = blackBGView.center;
    } completion:^(BOOL finished) {
        blackBGView.userInteractionEnabled = YES;
    }];
}
//缩小图片
- (void)closeView
{
    [UIView animateWithDuration:0.25f animations:^{
        bigImageView.frame = imageInWindowFrame;
        coverView.alpha = 0;
    } completion:^(BOOL finished) {
        blackBGView.hidden = YES;
    }];
}

#pragma mark - 上传图片
- (void)actionSheetDidSelect:(NSInteger)index
{
    if (index == 0 || index == 1) {
        
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
        //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
        //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
        PickerImage.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
        PickerImage.delegate = self;
        [self presentViewController:PickerImage animated:YES completion:nil];
    }
}
- (IBAction)clearImageButtonClick:(UIButton *)sender {
    
    switch (sender.tag) {
        case 100:
        {
            //界面变化
            self.cardImageView1.image = self.cardImageView2.image;
            self.cardImageView2.image = self.cardImageView3.image;
            self.cardImageView3.image = nil;

            if (self.imageName2.length > 0 && self.imageName3.length > 0)
            {
                self.addImageButton.frame = self.cardImageView3.frame;
                _selectImageIndex = 3;
                self.deleteButton3.hidden = YES;
            }
            else if (self.imageName2.length > 0 && self.imageName3.length <= 0)
            {
                self.addImageButton.frame = self.cardImageView2.frame;
                _selectImageIndex = 2;
                self.deleteButton2.hidden = YES;
            }
            else
            {
                self.addImageButton.frame = self.cardImageView1.frame;
                _selectImageIndex = 1;
                self.deleteButton1.hidden = YES;
            }
            
            //数据变化
            self.imageName1 = self.imageName2;
            self.imageName2 = self.imageName3;
            self.imageName3 = @"";
          
        }
            break;
        case 101:
        {
            //界面变化
            self.cardImageView2.image = self.cardImageView3.image;
            self.cardImageView3.image = nil;

            if (self.imageName3.length > 0)
            {
                self.addImageButton.frame = self.cardImageView3.frame;
                _selectImageIndex = 3;
                self.deleteButton3.hidden = YES;
            }
            else
            {
                self.addImageButton.frame = self.cardImageView2.frame;
                _selectImageIndex = 2;
                self.deleteButton2.hidden = YES;
            }
            
            //数据变化
            self.imageName2 = self.imageName3;
            self.imageName3 = @"";
        }
            break;
        case 102:
        {
            //界面变化
            self.cardImageView3.image = nil;
            
            self.addImageButton.frame = self.cardImageView3.frame;
            _selectImageIndex = 3;
            self.deleteButton3.hidden = YES;
            
            //数据变化
            self.imageName3 = @"";
            
        }
            break;
        default:
            break;
    }
    
}

//PickerImage完成后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *newPhoto = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    switch (_selectImageIndex) {
        case 1:
            self.cardImageView1.image = newPhoto;
            self.deleteButton1.hidden = NO;
            self.addImageButton.frame = self.cardImageView2.frame;
            break;
        case 2:
            self.cardImageView2.image = newPhoto;
            self.deleteButton2.hidden = NO;
            self.addImageButton.frame = self.cardImageView3.frame;
            break;
        case 3:
            self.cardImageView3.image = newPhoto;
            self.deleteButton3.hidden = NO;
            self.addImageButton.frame = CGRectZero;
            break;
        default:
            break;
    }
    
    //压缩图片
    NSData *fileData = UIImageJPEGRepresentation(newPhoto, 0.1);
    
    //获取正在编辑的图片
    
    __block NSURL *imageUrl = [info valueForKey:UIImagePickerControllerReferenceURL];
    
    __block NSString *imageName;
    //获取图片的名字信息
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        ALAssetRepresentation *representation = [myasset defaultRepresentation];
        imageName = [representation filename];//self.imageName是属性
        
        if (imageName == nil) imageName = [NSString stringWithFormat:@"%d.PNG", arc4random() % 10000];
        //上传图片
        [self uploadImageWithData:fileData imageName:imageName];
    };
    
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:imageUrl
                   resultBlock:resultblock
                  failureBlock:nil];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImageWithData:(NSData *)fileData imageName:(NSString *)imageName
{
    //1.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.上传文件
    NSDictionary *dict = @{};
    
    NSString *urlString = [NSString stringWithFormat:@"%@sid=%@", kUploadDriveCardAddress, getNSUser(kAPP_SID)];;
    
    [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //这个就是参数
        [formData appendPartWithFileData:fileData name:@"file" fileName:imageName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //请求成功
        NSLog(@"请求成功：%@",responseObject);
        
        if ([[responseObject valueForKey:@"code"] isEqualToString:@"S_OK"]) {
            [MBProgressHUD showTips:@"上传成功" toView:self.view];
            
            NSString *currentImageName = [NSMutableString stringWithFormat:@"%@", [responseObject valueForKey:@"var"]];
            
            switch (_selectImageIndex) {
                case 1:
                    self.imageName1 = currentImageName;
                    break;
                case 2:
                    self.imageName2 = currentImageName;
                    break;
                case 3:
                    self.imageName3 = currentImageName;
                    break;
                default:
                    break;
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //请求失败
        NSLog(@"请求失败：%@",error);
    }];
    
}

@end
